<!--
 * @author luguoxiang
 * @date 2022/9/17
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <t-tree :data="data" line expand-all v-bind="$attrs" />
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import api from './api';
import { toTreeData } from '@/soar';

const props = defineProps({
  /**
   * 数据处理器
   */
  handler: {
    type: Function,
    default: null,
  },
  /**
   * 前面的选项
   */
  prepend: {
    type: [Function, Array, Object],
    default() {
      return [];
    },
  },
  /**
   * 后面的选项
   */
  append: {
    type: [Function, Array, Object],
    default() {
      return [];
    },
  },
});
const emits = defineEmits(['load']);

const data = ref();

function load() {
  api.list({ $soarQuery: { fields: 'id,parentId,name' } }).then((res) => {
    // eslint-disable-next-line prefer-const
    let { handler, prepend, append } = props;
    if (typeof handler === 'function') {
      data.value = handler(res);
    } else {
      res.forEach((x) => {
        x.label = x.name;
        x.value = x.id;
        delete x.id;
        delete x.name;
        if (x.parentId === '0') {
          delete x.parentId;
        }
      });
      data.value = toTreeData(res, 'value', 'parentId');
    }
    if (prepend) {
      if (typeof prepend === 'function') {
        prepend = prepend();
      }
      if (Array.isArray(prepend)) {
        data.value = prepend.concat(data.value);
      } else {
        data.value.unshift(prepend);
      }
    }
    if (append) {
      if (typeof append === 'function') {
        append = append();
      }
      if (Array.isArray(append)) {
        data.value = data.value.concat(append);
      } else {
        data.value.push(append);
      }
    }
    emits('load', data.value.length ? [data.value[0].value] : [], data.value);
  });
}
onMounted(load);
</script>
<script lang="ts">
export default {
  name: 'OrgTree',
};
</script>
